iT邦幫忙

2023 iThome 鐵人賽

DAY 30
0
Software Development

LELECOCODE 每一天系列 第 30

Day 30 : Leetcode 小挑戰,30 Days of JavaScript

  • 分享至 

  • xImage
  •  

Day 30: Calculator with Method Chaining

Design a Calculator class. The class should provide the mathematical operations of addition, subtraction, multiplication, division, and exponentiation. It should also allow consecutive operations to be performed using method chaining. The Calculator class constructor should accept a number which serves as the initial value of result.

Your Calculator class should have the following methods:

add - This method adds the given number value to the result and returns the updated Calculator.
subtract - This method subtracts the given number value from the result and returns the updated Calculator.
multiply - This method multiplies the result by the given number value and returns the updated Calculator.
divide - This method divides the result by the given number value and returns the updated Calculator. If the passed value is 0, an error "Division by zero is not allowed" should be thrown.
power - This method raises the result to the power of the given number value and returns the updated Calculator.
getResult - This method returns the result.
Solutions within 10-5 of the actual result are considered correct.

class Calculator {
  
    /** 
     * @param {number} value
     */
	constructor(value) {
		
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	add(value){
		
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	subtract(value){
		
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */  
	multiply(value) {
		
	}

    /** 
     * @param {number} value
     * @return {Calculator}
     */
	divide(value) {
		
	}
  
    /** 
     * @param {number} value
     * @return {Calculator}
     */
	power(value) {
		
	}
    
    /** 
     * @return {number}
     */
	getResult() {
		
	}
}

Example 1:

Input:
actions = ["Calculator", "add", "subtract", "getResult"],
values = [10, 5, 7]
Output: 8

Example 2:
Input:
actions = ["Calculator", "multiply", "power", "getResult"],
values = [2, 5, 2]
Output: 100

Example 3:
Input:
actions = ["Calculator", "divide", "getResult"],
values = [20, 0]
Output: "Division by zero is not allowed"



上一篇
Day 29 : Leetcode 小挑戰,30 Days of JavaScript
系列文
LELECOCODE 每一天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言